package com.spsoft.vatoutinv.service.flowprocess;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.spsoft.core.enums.ResponseEnum;
import com.spsoft.core.exception.BusinessException;
import com.spsoft.core.model.ProcessParamBo;
import com.spsoft.core.model.Result;
import com.spsoft.vatoutinv.entity.matchflow.VmsMatching;
import com.spsoft.vatoutinv.service.matchflow.VmsMatchFlowRevokeService;
import com.spsoft.vatoutinv.service.matchflow.VmsMatchingService;
import com.spsoft.workflow.common.enums.bus.MatchFlowRevokeEnums;
import com.spsoft.workflow.service.BusinessHandlerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * 发票匹配流水申请流程处理业务实现类
 *
 * @author : chenxudong
 * @date : 2024/6/28 16:25
 */
@Service("FLOW_PPLSCX")
@Slf4j
@RequiredArgsConstructor
public class MatchFlowRevokeProcessHandlerServiceImpl implements BusinessHandlerService {

    private final VmsMatchingService vmsMatchingService;

    private final VmsMatchFlowRevokeService vmsMatchFlowRevokeService;

    @Override
    public void processHandler(ProcessParamBo param) throws BusinessException {
        Long busId = param.getBusId();
        String nodeId = param.getNodeId();
        MatchFlowRevokeEnums e = MatchFlowRevokeEnums.valueOfCode(nodeId);
        if (e == null) {
            throw new BusinessException(ResponseEnum.PARAM_VALIDATED_ERROR.getCode(), "审批流程有误，请联系管理员");
        }
        switch (e) {
            case ROOT:
                // 查询手工匹配流水记录是否存在
                LambdaQueryWrapper<VmsMatching> matchQuery = new LambdaQueryWrapper<>();
                matchQuery.eq(VmsMatching::getApplyId, busId);
                VmsMatching vmsMatching = vmsMatchingService.getOne(matchQuery);
                if (vmsMatching == null) {
                    throw new BusinessException(ResponseEnum.MATCH_FLOW_NOT_FIND_ERROR);
                }
                break;
            case FLOW_PPLSCX_SP:
                /**
                 * 审批节点
                 * 1、判断当前发票的匹配状态是否为已匹配、明细匹配的流水是否为已开票状态
                 * 2、删除发票明细和匹配流水的关联关系
                 * 3、将发票的匹配状态修改为未匹配、流水的开票状态修改为未开票、清空匹配时间
                 */
                Result<Object> result = vmsMatchFlowRevokeService.matchFlowRevokeProcess(busId);
                if (!ResponseEnum.SUCCESS.getCode().equals(result.getCode())) {
                    throw new BusinessException(result.getCode(), result.getMessage());
                }
                break;
            default:
                // 未知节点报错
                throw new BusinessException(ResponseEnum.PROCESS_NODE_ERROR);
        }
    }
}
